#include "settings.h"
#include <QtGui>

Settings::Settings(QWidget *parent):
        QDialog(parent)
{
    setModal(true);
    setWindowTitle(qApp->property("appRealName").toString()+"::"+DEFAULT_WINDOW_NAME);
    setMinimumSize(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT);

    informationAreaL = new QLabel(this);
    informationAreaL->setMinimumHeight(30);
    informationAreaL->hide();

    __username = "";
    __password = "";

    //Main
    QWidget *tabMain = new QWidget(this);
    username = new QLineEdit(this);
    password = new QLineEdit(this);
        password->setEchoMode(QLineEdit::Password);
    updateTime = new QSpinBox(this);
        updateTime->setRange(DEFAULT_MIN_UPDATE_TIME, DEFAULT_MAX_UPDATE_TIME);
        updateTime->setSuffix(tr("min"));
        updateTime->setAlignment(Qt::AlignRight);

    QLabel *usernameL = new QLabel(tr("User name or email address:"), this);
        usernameL->setBuddy(username);
    QLabel *passwordL = new QLabel(tr("Password:"), this);
        passwordL->setBuddy(password);
    QLabel *updateTimeL = new QLabel(tr("Update interval:"), this);
        updateTimeL->setBuddy(updateTime);

    QVBoxLayout *authLayout = new QVBoxLayout();
        authLayout->addWidget(usernameL);
        authLayout->addWidget(username);
        authLayout->addWidget(passwordL);
        authLayout->addWidget(password);

    QGroupBox *authGroup = new QGroupBox(tr("Authentification"), this);
        authGroup->setLayout(authLayout);

    QHBoxLayout *updateTimeLayout = new QHBoxLayout();
        updateTimeLayout->addWidget(updateTimeL);
        updateTimeLayout->addWidget(updateTime);

    QVBoxLayout *tabMainLayout = new QVBoxLayout();
        tabMainLayout->addWidget(authGroup);
        tabMainLayout->addLayout(updateTimeLayout);
        tabMainLayout->addStretch(1);

    tabMain->setLayout(tabMainLayout);

    //Style
    QWidget *tabStyle = new QWidget(this);
        statusOwnerColorBtn = new QPushButton(this);
        usersColorBtn = new QPushButton(this);
        linksColorBtn = new QPushButton(this);

        QLabel *statusOwnerColorL = new QLabel(tr("Status owner color"), this);
            statusOwnerColorL->setBuddy(statusOwnerColorBtn);
        QLabel *usersColorL = new QLabel(tr("Users color"), this);
            usersColorL->setBuddy(usersColorBtn);
        QLabel *linksColorL = new QLabel(tr("Links color"), this);
            linksColorL->setBuddy(linksColorBtn);

        statusOwnerBold = new QCheckBox(tr("Bold"), this);
        usersBold = new QCheckBox(tr("Bold"), this);
        linksBold = new QCheckBox(tr("Bold"), this);

        QHBoxLayout *statusOwnerColorLayout = new QHBoxLayout();
            statusOwnerColorLayout->addWidget(statusOwnerColorL, 1);
            statusOwnerColorLayout->addWidget(statusOwnerColorBtn,0, Qt::AlignRight);
            statusOwnerColorLayout->addWidget(statusOwnerBold,0, Qt::AlignRight);
        QHBoxLayout *usersColorLayout = new QHBoxLayout();
            usersColorLayout->addWidget(usersColorL, 1);
            usersColorLayout->addWidget(usersColorBtn,0, Qt::AlignRight);
            usersColorLayout->addWidget(usersBold,0, Qt::AlignRight);
        QHBoxLayout *linksColorLayout = new QHBoxLayout();
            linksColorLayout->addWidget(linksColorL, 1);
            linksColorLayout->addWidget(linksColorBtn,0, Qt::AlignRight);
            linksColorLayout->addWidget(linksBold,0, Qt::AlignRight);

        QVBoxLayout *statusColorLayout = new QVBoxLayout();
            statusColorLayout->addLayout(statusOwnerColorLayout);
            statusColorLayout->addLayout(usersColorLayout);
            statusColorLayout->addLayout(linksColorLayout);
            statusColorLayout->addStretch(1);

        QGroupBox *statusColorGrp = new QGroupBox(tr("Status colors"), this);
            statusColorGrp->setLayout(statusColorLayout);

        QVBoxLayout *tabStyleLayout = new QVBoxLayout();
            tabStyleLayout->addWidget(statusColorGrp);
            tabStyleLayout->addStretch(1);

    tabStyle->setLayout(tabStyleLayout);
    connect(statusOwnerColorBtn, SIGNAL(released()), this, SLOT(changeStatusOwnerColor()));
    connect(usersColorBtn, SIGNAL(released()), this, SLOT(changeUsersColor()));
    connect(linksColorBtn, SIGNAL(released()), this, SLOT(changeLinksColor()));


    //TABWIDGET
    QTabWidget *tabs = new QTabWidget(this);
    tabs->addTab(tabMain, tr("Main"));
    tabs->addTab(tabStyle, tr("Style"));

    //SAVE BUTTON
   saveSettingsBtn = new QPushButton(tr("Save Settings"), this);

    QVBoxLayout *mainLauoyt = new QVBoxLayout();
    mainLauoyt->addWidget(informationAreaL);
    mainLauoyt->addWidget(tabs);
    mainLauoyt->addWidget(saveSettingsBtn, 0, Qt::AlignRight);
    setLayout(mainLauoyt);

    connect(saveSettingsBtn, SIGNAL(clicked(bool)), this, SLOT(saveSettingsClicked()));

    //QSettings use setApplicationName, setOrganizationName from main();
    settings = new QSettings();
    loadSettings();
}

QString Settings::getUsername()
{
    return username->text();
}

QString Settings::getPassword()
{
    return password->text();
}

void Settings::informationArea(QString text, bool isError)
{
    QString errorStyle =  "border: 2px solid #E20700; background-color:#F9CCCA;";
    QString noerrorStyle = "border: 2px solid #008C00; background-color:#BFFFBF;";
    isError ? informationAreaL->setStyleSheet(errorStyle) : informationAreaL->setStyleSheet(noerrorStyle);
    informationAreaL->setText("<center>" + text + "</center>");
    informationAreaL->show();
    QTimer::singleShot(5000, informationAreaL, SLOT(hide()));
}

void Settings::loginCallBack(bool isError)
{
    QString error = tr("You enter wrong user name or pasword");
    QString noerror = tr("Authentication was successful");
    if(isError)
    {
        show();
        informationArea(error, true);
    } else {
        informationArea(noerror, false);
        __username = username->text();
        __password = password->text();
        QTimer::singleShot(1000, this, SLOT(saveSettingsClicked()));
    }
    saveSettingsBtn->setDisabled(false);
}

bool Settings::isLoginInfoExist()
{
    if(username->text().isEmpty() || password->text().isEmpty())
    {
        informationArea(tr("User name and password must be set."), true);
        return false;
    } else {
        return true;
    }
}

void Settings::saveSettingsClicked()
{
    if(isLoginInfoExist())
    {
        if(__username != username->text() || __password != password->text())
        {
            saveSettingsBtn->setDisabled(true);
            emit newLoginInfo();
        } else {
            hide();
            saveSettings();
            emit settingsChanged();
        }
    }
}

void Settings::loadSettings()
{
    settings->beginGroup("Window");
        windowPosition.setX(settings->value("window_x", DEFAULT_WINDOW_POS_X).toInt());
        windowPosition.setY(settings->value("window_y", DEFAULT_WINDOW_POS_Y).toInt());
        windowSize.setWidth(settings->value("window_w", DEFAULT_WINDOW_WIDTH).toInt());
        windowSize.setHeight(settings->value("window_h", DEFAULT_WINDOW_HEIGHT).toInt());
        toolBarState = settings->value("toolBarState").toByteArray();
        cacheDir = settings->value("CacheDir", QDir::homePath() + "/." + qApp->applicationName() + "/cache").toString();
    settings->endGroup();
    settings->beginGroup("Main");
        __username = settings->value("username").toString();
        username->setText(__username);
        __password = settings->value("password").toString();
        password->setText(__password);
        updateTime->setValue(settings->value("updateTime", "3").toInt());
    settings->endGroup();
    settings->beginGroup("StatusStyle");
        statusOwnerColor = settings->value("StatusOwnerColor", "#FF0000").toString();
        statusOwnerBold->setChecked(settings->value("StatusOwnerBold", true).toBool());
        usersColor = settings->value("UsersColor", "#FF0000").toString();
        usersBold->setChecked(settings->value("UsersBold", false).toBool());
        linksColor = settings->value("LinksColor", "#FF0000").toString();
        linksBold->setChecked(settings->value("LinksBold", false).toBool());
    settings->endGroup();

    statusOwnerColorBtn->setIcon(createIconForBtn(statusOwnerColor));
    usersColorBtn->setIcon(createIconForBtn(usersColor));
    linksColorBtn->setIcon(createIconForBtn(linksColor));
}

void Settings::saveSettings()
{
    settings->beginGroup("Window");
        settings->setValue("window_x", windowPosition.x());
        settings->setValue("window_y", windowPosition.y());
        settings->setValue("window_w", windowSize.width());
        settings->setValue("window_h", windowSize.height());
        settings->setValue("toolBarState", toolBarState);
        settings->setValue("CacheDir", cacheDir);
    settings->endGroup();
    settings->beginGroup("Main");
        settings->setValue("username", username->text());
        settings->setValue("password", password->text());
        settings->setValue("updateTime", updateTime->value());
    settings->endGroup();
    settings->beginGroup("StatusStyle");
        settings->setValue("StatusOwnerColor", statusOwnerColor.name());
        settings->setValue("StatusOwnerBold", statusOwnerBold->isChecked());
        settings->setValue("UsersColor", usersColor.name());
        settings->setValue("UsersBold", usersBold->isChecked());
        settings->setValue("LinksColor", linksColor.name());
        settings->setValue("LinksBold", linksBold->isChecked());
    settings->endGroup();
    settings->sync();
}

void Settings::changeStatusOwnerColor()
{
    QColor _statusOwnerColor = QColorDialog::getColor(statusOwnerColor, this);
    if(_statusOwnerColor.isValid())
    {
        statusOwnerColor = _statusOwnerColor;
        statusOwnerColorBtn->setIcon(createIconForBtn(statusOwnerColor));
    }
}

void Settings::changeUsersColor()
{
    QColor _usersColor = QColorDialog::getColor(usersColor, this);
    if(_usersColor.isValid())
    {
        usersColor = _usersColor;
        usersColorBtn->setIcon(createIconForBtn(usersColor));
    }
}

void Settings::changeLinksColor()
{
    QColor _linksColor = QColorDialog::getColor(linksColor, this);
    if(_linksColor.isValid())
    {
        linksColor = _linksColor;
        linksColorBtn->setIcon(createIconForBtn(linksColor));
    }
}

QIcon Settings::createIconForBtn(const QColor &color)
{
    QPixmap pix(16, 16);
    pix.fill(color);
    return QIcon(pix);
}

void Settings::updateToolBarState(const QByteArray &state)
{
    toolBarState = state;
}

QByteArray Settings::getToolBarState()
{
    return toolBarState;
}

QString Settings::getStatusOwnerColor()
{
    return statusOwnerColor.name();
}

QString Settings::getUsersColor()
{
    return usersColor.name();
}

QString Settings::getLinksColor()
{
    return linksColor.name();
}

int Settings::getUpdateTime()
{
    return updateTime->value() * 60000;
}

QSize Settings::getWindowSize()
{
    return windowSize;
}

QPoint Settings::getWindowPosition()
{
    return windowPosition;
}

bool Settings::getIsStatusOwnerBold()
{
    return statusOwnerBold->isChecked();
}

bool Settings::getIsUsersBold()
{
    return usersBold->isChecked();
}

bool Settings::getIsLinksBold()
{
    return linksBold->isChecked();
}

QString Settings::getCacheDir()
{
    return cacheDir;
}

void Settings::updateWindowSize(int w, int h)
{
    windowSize.setWidth(w);
    windowSize.setHeight(h);
}

void Settings::updateWindowPosition(int x, int y)
{
    windowPosition.setX(x);
    windowPosition.setY(y);
}

void Settings::closeEvent(QCloseEvent *event)
{
    if(__username != "" && __password != "")
    {
        username->setText(__username);
        password->setText(__password);
        event->accept();
    } else {
        event->ignore();
    }
}

Settings::~Settings()
{
    saveSettings();
}
